// pages/user/order/order.js
import orderIndex  from '../../../api/order';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    headerHeight:app.globalData.headerHeight,
    pageNo:1,
    pageSize:20,
    status:100,
    servicetimeInterval:'',
    systimestamp:'',
    orderList:[],
    isTrue:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      status:options.status||'100'
    })
    this.getOrderList()
  },
  getOrderList(){
      var opt={
        pageNo:this.data.pageNo,
        pageSize:this.data.pageSize,
        status:this.data.status
      }
      orderIndex.apiOrderList(opt).then(res=>{
        if(opt.pageNo==1){
          var orderList=res.data.map(res=>{
            res.productImgs=res.productImgs.split(',')
            res.endTime=''
            if(res.status==0){
              res.endTime=this.getendTime(res.createTime)
            }
            return res
          })
        }else{
          var dataList=res.data.map(res=>{
            res.productImgs=res.productImgs.split(',')
            res.endTime=''
            if(res.status==0){
              res.endTime=this.getendTime(res.createTime)
            }
            return res
          })
          var orderList=this.data.orderList.concat(dataList)
        }
        console.log(orderList,'orderListorderList')
        var isMore=false
        if(res.data.length<opt.pageSize){
          isMore=true
        }
        this.setData({
          orderList:orderList,
          isMore:isMore,
        })
      })
  },
  getendTime(time){
    let now = new Date(time); // 获取当前时间
    // 将当前时间加上24小时
    let futureTime = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 24小时的毫秒数 
    // 格式化时间为年-月-日 时:分:秒
    let year = futureTime.getFullYear();
    let month = String(futureTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1，并使用padStart确保是两位数
    let day = String(futureTime.getDate()).padStart(2, '0');
    let hours = String(futureTime.getHours()).padStart(2, '0');
    let minutes = String(futureTime.getMinutes()).padStart(2, '0');
    let seconds = String(futureTime.getSeconds()).padStart(2, '0'); 
    let formattedDate = `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    return formattedDate
  },
  onScrolltolower(){
    if(this.data.isMore){
      this.setData({
        pageNo:this.data.pageNo+1
      })
      this.getOrderList()
    }
  },
  //取消订单
  cancellationOrder(e){
    var item=e.currentTarget.dataset.item
    var opt={
      orderNo:item.orderNo
    }
    var that=this
    if(item.status==1){
      wx.requestSubscribeMessage({
        tmplIds: ['SRsRyuTY8dIxP61UcjuhNlTThi9T-_8aaGzYNjutpHg'],
        complete (complete) {
          wx.showModal({
            title: '提示',
            content: '确认取消当前订单？',
            success (res) {
              if (res.confirm) {
                if(that.data.isTrue){
                  that.setData({
                    isTrue:false
                  })
                  orderIndex.apiCancelOrder(opt).then(res=>{
                    wx.showToast({
                      title:'订单取消成功',
                        icon: 'none',
                        duration:3000,
                      }) 
                      that.setData({
                        pageNo:1,
                        isTrue:true
                      })
                      that.getOrderList()
                  }).finally(()=>{
                    that.setData({
                      isTrue:true
                    })
                  })
                }else{
                  wx.showToast({
                    title:'请勿连续操作，请10s后再试',
                      icon: 'none',
                      duration:3000,
                    }) 
                  setTimeout(()=>{
                    that.setData({
                      isTrue:true
                    })
                  },10000)
                }
                
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '确认取消当前订单？',
        success (res) {
          if (res.confirm) {
            if(that.data.isTrue){
              that.setData({
                isTrue:false
              })
              orderIndex.apiCancelOrder(opt).then(res=>{
                wx.showToast({
                  title:'订单取消成功',
                    icon: 'none',
                    duration:3000,
                  }) 
                  that.setData({
                    pageNo:1,
                    isTrue:true
                  })
                  that.getOrderList()
              }).finally(()=>{
                that.setData({
                  isTrue:true
                })
              })
            }else{
              wx.showToast({
                title:'请勿连续操作，请10s后再试',
                  icon: 'none',
                  duration:3000,
                }) 
              setTimeout(()=>{
                that.setData({
                  isTrue:true
                })
              },10000)
            }
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  confirmReceiptGoods(e){
    var item=e.currentTarget.dataset.item
    var opt={
      orderNo:item.orderNo
    }
    var that=this
    wx.showModal({
      title: '提示',
      content: '请先确认已经收到货',
      success (res) {
        if (res.confirm) {
          orderIndex.apiConfirmReceipt(opt).then(res=>{
            wx.showToast({
              title:'确认收货成功',
                icon: 'none',
                duration:3000,
              }) 
              that.setData({
                pageNo:1
              })
              that.getOrderList()
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
   //再来一单
   buyAgain(e){
    var item=e.currentTarget.dataset.item
    var opt={
      orderNo:item.orderNo
    }
    var that=this
    wx.showModal({
      title: '提示',
      content: '确认再次购买当前产品？',
      success (res) {
        if (res.confirm) {
          orderIndex.apiOneMoreOrder(opt).then(res=>{
            var row=res.data.details
            wx.setStorageSync('shopCartList', row)
            wx.navigateTo({
              url: '/pages/home/orderConfirm/orderConfirm',
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  behalfPay(e){
    var item=e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/home/behalfPayment/behalfPayment?amount=${item.amount}&orderNo=${item.orderNo}&type=share`,
    })
  },
  //查看物流
  getlogistics(e){
    var item=e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/user/logistics/logistics?orderNo=${item.orderNo}&&type=1`,
    })
  },
  //申请发票
  getInvoice(e){
    var item=e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/user/invoice/invoice?orderNo=${item.orderNo}`,
    })
  },
  //立即支付
  payNow(e){
    var item=e.currentTarget.dataset.item
    this.payOrder(item.orderNo,item.relAmount)
  },
  payOrder(orderNo,amount){
    var that=this
    wx.showLoading({
      title: '支付中'
    });
    orderIndex.apiSubmiPay({orderNo:orderNo}).then(res=>{
      wx.requestPayment({
        timeStamp:res.data.timeStamp,
        nonceStr:res.data.nonceStr,
        package:res.data.package,
        signType:res.data.signType,
        paySign:res.data.paySign,
        success: (res) => {
          setTimeout(function () {
            wx.hideLoading();
          }, 1500)
          if(res.resultCode==6001){
            wx.showToast({
              title:'取消支付',
              icon: 'none',
              duration:3000,
              success: function () {
                setTimeout(function () {
                  wx.hideLoading();
                }, 1500)
              }
            }) 
          }else if(res.resultCode==6002){
          wx.showToast({
            title:'网络连接出错,请检查网络连接后重试',
              icon: 'none',
              duration:3000,
              success: function () {
                setTimeout(function () {
                  wx.hideLoading();
                }, 1500)
              }
            }) 
          }else{
           wx.redirectTo({
             url: `/pages/home/payResult/payResult?amount=${amount}&&orderNo=${orderNo}`,
           })
          }
        },
        fail: (res) => {
          console.log(res)
          wx.showToast({
            title:"取消支付",
            icon: "none",
            duration:3000
          })
      
        }
      });
    })
    // wx.navigateTo({
    //   url: `/pages/home/choosePay/choosePay?amount=${amount}&&orderNo=${orderNo}`,
    // })
  },
//订单
getOrder(e){
  var status=e.currentTarget.dataset.status
  this.setData({
    status:status,
    pageNo:1,
  })
  this.getOrderList()
},
//详情
getOrderDetais(e){
  var item=e.currentTarget.dataset.item
  wx.navigateTo({
    url: `/pages/user/orderDetails/orderDetails?orderNo=${item.orderNo}`,
  })
},
//售后订单
afterSalesOrder(){
  wx.navigateTo({
    url: `/pages/user/afterSalesOrder/afterSalesOrder`,
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var serverLocalDate = new Date().getTime();
    //调用函数开始计时
    this.serverLocalDate(serverLocalDate);
  },
  //服务器系统时间开始计时
  serverLocalDate: function (serverLocalDate) {
    console.log(serverLocalDate)
    var _this = this;
    let newDate = serverLocalDate;
    _this.setData({
      servicetimeInterval: setInterval(function () { // 循环执行  
        newDate = (newDate / 1000 + 1) * 1000;
        _this.setData({
          systimestamp: newDate
        })
      }, 1000)  // 每秒执行一次以达到更新时间的目的
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.servicetimeInterval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.servicetimeInterval)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})